﻿using System;
using System.Net;
using System.Windows;

namespace Alfa.Common.UI.Dialogs {
	/// <summary>
	/// Window for displaing throwned error in your application.
	/// User can decide in restart, close or report error to you.
	/// You can send exception to your web serwer.
	/// Interaction logic for ErrorMsgWindow.xaml
	/// </summary>
	public partial class ErrorMessageWindow : Window {
		Exception exception;
		string reportUri;

		/// <summary>
		/// Standard constructor for Window
		/// </summary>
		private ErrorMessageWindow( ) {
			InitializeComponent( );
			this.Title = Messages.ProgramError;
			this.textBoxErrorMessage.Text = Messages.ErrorMessage;
			this.buttonClose.Content = Messages.CloseApplication;
			this.buttonRestart.Content = Messages.RestartApplication;
			this.buttonReportError.Content = Messages.ReportError;
			this.reportUri = "http://apps.alfa.eu/Alfa.Common/BugTracer";
		}

		/// <summary>
		/// Use this constructor to provide exception to window.
		/// </summary>
		/// <param name="ex">Throwned exception.</param>
		public ErrorMessageWindow(Exception ex)
			: this( ) {
			this.exception = ex;
		}

		/// <summary>
		/// Use this constructor to provide exception and address of your web repporting server to window.
		/// </summary>
		/// <param name="ex">Throwned exception.</param>
		/// <param name="reportUri">Uri contains web address of your web repporting server.</param>
		public ErrorMessageWindow(Exception ex, string reportUri)
			: this(ex) {
			this.reportUri = reportUri;
		}

		private void ButtonRerun_Click(object sender, RoutedEventArgs e) {
			this.Hide( );
			System.Diagnostics.Process.Start(AppInfo.ExecutablePath.FullName);
			this.Close( );
		}

		private void ButtonReport_Click(object sender, RoutedEventArgs e) {
			this.buttonReportError.IsEnabled = false;
			if (this.exception != null) {
				Exception exc = exception;
				reportUri += "?outer=" + this.exception.GetType( ).ToString( );
				int innerId = 0;
				while ((exc = exc.InnerException) != null && innerId > 5) {
					string suffix = (innerId > 0 ? innerId.ToString( ) : "");
					reportUri += "&&inner" + suffix + "=" + exc.GetType( ).ToString( );
					reportUri += "&&inner" + suffix + "msg=" + exc.Message.ToString( );
					innerId++;
				}
				reportUri += "&&msg=" + this.exception.Message.ToString( );
				WebClient webClient = new WebClient( );
				try {
					webClient.DownloadString(reportUri);
				} catch {
				}
				this.Close( );
			}
		}

		private void ButtonClose_Click(object sender, RoutedEventArgs e) {
			this.Close( );
		}

		private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e) {
			if (Application.Current != null)
				Application.Current.Shutdown( );
		}
	}
}
